package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.result.Result;
import com.dongdongshop.result.ResultEnum;
import com.dongdongshop.service.GoodsService;
import com.dongdongshop.service.ItemPageService;
import com.dongdongshop.util.PageUtil;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.rocketmq.spring.core.RocketMQTemplate;

import javax.annotation.Resource;

@Controller
@RequestMapping("goods")
public class GoodsController {

    private static final Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @Reference
    private GoodsService goodsService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @RequestMapping("toGoodsAudit")
    public String toGoodsAudit(){
        return "admin/goods";
    }

    @RequestMapping("getListGoods")
    @ResponseBody
    public Result<PageUtil<TbGoods>> getListGoods(String goodsName, @RequestParam(defaultValue = "-1") String auditStatus, @RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                                  @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        try {
            PageInfo<TbGoods> pageInfo = goodsService.getListGoods(goodsName,auditStatus,pageNumber,pageSize);
            PageUtil<TbGoods> pageUtil = new PageUtil<>();
            pageUtil.setPageNumber(pageNumber);
            pageUtil.setPageSize(pageSize);
            pageUtil.setList(pageInfo.getList());
            pageUtil.setTotal(pageInfo.getTotal());
            return Result.jsonResponse(ResultEnum.OK).setData(pageUtil);
        }catch (Exception e){
            logger.error("系统报错",e);
            return Result.jsonResponse(ResultEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("updateGoodsAuditStatus")
    @ResponseBody
    public Result updateGoodsAuditStatus(@RequestParam("ids[]") Long[] ids,@RequestParam("auditStatus") String auditStatus){
        try {
            int i = goodsService.updateGoodsAuditStatus(ids,auditStatus);
            if (i > 0){
                if (auditStatus.equals("2")){
                    rocketMQTemplate.convertAndSend("ddItemPage",ids);
                }
            }
            return Result.jsonResponse(ResultEnum.OK);
        }catch (Exception e){
            logger.error("系统报错",e);
            return Result.jsonResponse(ResultEnum.INTERNAL_SERVER_ERROR);
        }
    }


}
